package cn.sstir.hackathon.core.tsv;

import cn.sstir.hackathon.core.AbstractExportMap;
import com.univocity.parsers.tsv.TsvWriter;
import com.univocity.parsers.tsv.TsvWriterSettings;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author: fli
 * @email: fli@sstir.cn
 * @date: 2020/1/16 14:07
 */
public class TsvUtil {


    public static void exportTsv(Class<? extends AbstractExportMap> clazz, List<String> columns, List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws Exception{
        List<String> heads = new ArrayList<>();
        List<Object[]> data = new ArrayList<>();
        AbstractExportMap abstractExportMap = clazz.newInstance();
        for (String column : columns) {
            String columnName = abstractExportMap.get(column);
            if(columnName != null){
                heads.add(columnName);
            }
        }
        for (Map<String, Object> map : list) {
            List<Object> row = new ArrayList<>();
            for (String column : columns) {
               row.add(map.get(column));
            }
            data.add(row.toArray(new Object[row.size()]));
        }
        exportTsv(heads.toArray(new String[heads.size()]),data,fileName,response);
    }

    /**
     * @param  heads 标题头
     * @param fileName  文件名
     * @param data 数据
     * @author fli
     * @date 2020/1/16 13:55
     */
    public static void exportTsv(  String[] heads, List<Object[]> data, String fileName, HttpServletResponse response) throws Exception {
        TsvWriterSettings settings = new TsvWriterSettings();
        settings.setIgnoreLeadingWhitespaces(false);
        settings.setIgnoreTrailingWhitespaces(false);
        settings.setHeaders(heads);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")+".tsv");
        OutputStream outputStream = response.getOutputStream();
        TsvWriter writer = new TsvWriter(new OutputStreamWriter(outputStream, "UTF-8"), settings);
        writer.writeHeaders();
        writer.writeRows(data);
        writer.close();
        try {
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
